package com.thread;



import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;










import org.eclipse.swt.widgets.Display;
import org.eclipse.wb.swt.SWTResourceManager;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.bean.LoginBean;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import com.https.HttpHeader;
import com.https.UrlConstants;
import com.ui.MainWindow;

/**
* @ClassName: LoginThread
* @Description: TODO
* @author alterhu2020@gmail.com
* @date Feb 15, 2014 9:27:24 PM
* 
*/

public class LoginThread extends Thread {

	private LoginBean bean;
	private MainWindow window;
	public LoginThread(LoginBean bean,MainWindow window) {
		// TODO Auto-generated constructor stub
		this.bean=bean;
		this.window=window;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		//boolean isok=false;
		//int relogged=0;
		while(!window.islogged){
			String user=bean.getUsername();
			String password=bean.getPassword();
			String passcode=bean.getPasscode();
			
			Display.getDefault().asyncExec(new Runnable() 
			 { 
			 public void run() 
			 { 
				 window.button_login.setText("正在登陆中...");
				 window.button_login.setEnabled(false);
			 } 
			 });
			
			window.logger("已经启动了登录的操作了，现在正在进行登录12306系统......");
			//检查验证码
			 Multimap<String, String> randomcodemap = LinkedListMultimap.create();
		    	
	    	 randomcodemap.put("randCode", passcode);
	    	 randomcodemap.put("rand", "sjrand");
	    	 
	    	 String check_result;
			try {
				check_result = window.client.postRequest(UrlConstants.URL_LOGIN_CHECK_PASSCODE, randomcodemap, HttpHeader.postCheckCode(), null);
			
				 JSONObject code_check_json=JSONObject.fromObject(check_result);
		    	 String data=code_check_json.getString("data");
		    	 if(data.equals("N")){
		    		window.logger("你输入的验证码错误，请重新输入！已经正在重新生成验证码"); 
		    		window.config.generatePasscode(window);
		    		//重新生成验证码
		    		
		    		 Display.getDefault().asyncExec(new Runnable() 
		    		 { 
		    		 public void run() 
		    		 { 
		    			 SWTResourceManager.disposeImages();
						 window.lblNewLabel_logincode.setImage(SWTResourceManager.getImage(window.login_image));
						 window.lblNewLabel_logincode.redraw();
						 window.text_logincode.setText("");
						 window.button_login.setText("再次登录");
						 window.button_login.setEnabled(true);
		    		 } 
		    		 });
		    		
		    		break;
		    	 }else{
		    		 window.logger("校验你输入的验证码正确,等候片刻我们发送信息进行登录中......");
		    	 }
		    	 
			} catch (KeyManagementException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	//登录请求
			/* try {
				SimplePlayer.playClip("/com/images/message.wav");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}*/
			
			try {
				Multimap<String, String> params = LinkedListMultimap.create();
				params.put("loginUserDTO.user_name",user);
				params.put("userDTO.password", password);
				params.put("randCode", passcode);
				String msg = window.client.postRequest(UrlConstants.URL_LOGIN_SUBMIT, params, HttpHeader.postCheckCode(), null);
			    System.out.println("登陆请求中服务器返回的值为: "+msg);
				JSONObject content=JSONObject.fromObject(msg);
			    JSONArray popmsg= content.getJSONArray("messages");
			    window.logger("登录后服务器返回的数据为: "+popmsg);
			    if(!popmsg.toString().equals("[]")){
			    	window.logger("发现服务器返回的数据不正确，程序将退出登录，请您稍后再重新尝试登录...");
			    	if(popmsg.toString().contains("23：00至07：00为系统维护时间")){
			    		window.logger("亲，铁道部都说了这个点他在搞腾维护，你还不休息下，又在做甚！你是火星人吗？");
			    		break;
			    	}
			    	window.config.generatePasscode(window);
			    	//重新生成验证码
			    	 Display.getDefault().asyncExec(new Runnable() 
		    		 { 
		    		 public void run() 
		    		 { 
		    			 SWTResourceManager.disposeImages();
						 window.lblNewLabel_logincode.setImage(SWTResourceManager.getImage(window.login_image));
						 window.lblNewLabel_logincode.redraw();
						 window.text_logincode.setText("");
						 window.button_login.setText("再次登录");
						 window.button_login.setEnabled(true);
		    		 } 
		    		 });
			    	break;
			    }
			} catch (Exception e) {
				window.logger("检查用户登录请求遇到了异常情况，返回值是 : "+e);
			}
		
			// login 
			String isloggedmsg=null;
			try {
				Multimap<String, String> homeparameter = ArrayListMultimap.create();
				homeparameter.put("_json_att", "");
				isloggedmsg=window.client.postRequest(UrlConstants.URL_LOGGED_INIT, homeparameter, HttpHeader.login(), null);	
			} catch (Exception e) {
				window.logger("登录用户失败，错误 : "+e);
			}
			
			if(isloggedmsg==null){
	    		window.logger("好的，用户:"+user+", 你已经登录了12306网站，现在开始抢票吧...");
	    		//frame.
	    		window.islogged=true;
	    		
	    		//登录后获得对应的cookies和联系人的信息设置
	    		//window.button_login.setText("登录成功");
	    	/*	String from=window.text_from.getText().trim();
	    		String to=window.text_to.getText().trim();
				Calendar instance = Calendar.getInstance();
				instance.set(Calendar.DAY_OF_MONTH, window.dateTime_date.getDay());
				instance.set(Calendar.MONTH, window.dateTime_date.getMonth());
				instance.set(Calendar.YEAR, window.dateTime_date.getYear());
				String traindate = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
				
	    	    window.getCookie(window.cookies, from, to,traindate); 
	    	    window.logger("由于你已经登录了系统，我们已经初始化了此次的登录cookies到网站");
	    	    */
	    		
	    		//break;
	    	}else{
	    		window.logger("对不起，现在登录12306失败，可能12306屏蔽了我们了！");
	    	}
			
			 Display.getDefault().asyncExec(new Runnable() 
    		 { 
    		 public void run() 
    		 { 
    			 window.button_login.setText("退出");
    			 window.button_login.setEnabled(true);
    				
    		 } 
    		 });
	    	
		} //while
				
	}
	



}
